package org.dbstar.scheduler.control.db.conf;

import java.sql.Types;
import java.util.List;

import net.sf.json.JSONSerializer;

import org.dbstar.scheduler.beans.JobConf;
import org.dbstar.scheduler.beans.ParameterDefine;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.SqlUpdate;


/**
 * JobInfo的Update对象
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-4-24
 */
public class JobConfUpdate extends SqlUpdate {
	public JobConfUpdate(JdbcTemplate jdbcTemplate) {
		super();
		setJdbcTemplate(jdbcTemplate);
		setSql("UPDATE SCHD_JOB_CONF SET CATALOG=?, TYPE=?, NAME=?, DESCRIPTION=?, RESOURCE=?, CONTENT=?, PARAMETER_SIZE=?, PARAMETER_DATA=?, MAX_RETRY=?, MODIFY_TIME=?, OWNER=?, MODIFIER=? WHERE SYSTEM_IDENTIFIER=? AND SEQUENCE=?");
		declareParameter(new SqlParameter("CATALOG", Types.INTEGER));
		declareParameter(new SqlParameter("TYPE", Types.VARCHAR));
		declareParameter(new SqlParameter("NAME", Types.VARCHAR));
		declareParameter(new SqlParameter("DESCRIPTION", Types.VARCHAR));
		declareParameter(new SqlParameter("RESOURCE", Types.VARCHAR));
		declareParameter(new SqlParameter("CONTENT", Types.VARCHAR));
		declareParameter(new SqlParameter("PARAMETER_SIZE", Types.INTEGER));
		declareParameter(new SqlParameter("PARAMETER_DATA", Types.VARCHAR));
		declareParameter(new SqlParameter("MAX_RETRY", Types.INTEGER));
		declareParameter(new SqlParameter("MODIFY_TIME", Types.BIGINT));
		declareParameter(new SqlParameter("OWNER", Types.VARCHAR));
		declareParameter(new SqlParameter("MODIFIER", Types.VARCHAR));
		declareParameter(new SqlParameter("SYSTEM_IDENTIFIER", Types.VARCHAR));
		declareParameter(new SqlParameter("SEQUENCE", Types.INTEGER));
	}

	public int updateJobConf(JobConf conf) {
		long modifyTime = System.currentTimeMillis();
		int result = update(conf.getCatalog(), conf.getType(), conf.getName(), conf.getDescription(),
				conf.getResource(), conf.getContent(), conf.getParameterSize(),
				parseParametersJson(conf.getParameters()), conf.getMaxRetry(), modifyTime, conf.getOwner(),
				conf.getModifier(), conf.getIdentifier().getSystemIdentifier(), conf.getIdentifier().getSequence());
		conf.setModifyTime(modifyTime);
		return result;
	}

	private String parseParametersJson(List<ParameterDefine> parameters) {
		if (parameters == null || parameters.isEmpty()) {
			return null;
		} else {
			return JSONSerializer.toJSON(parameters, new ParameterDefineJsonConfig()).toString();
		}
	}
}
